package club.justwill.single.helper;

import club.justwill.single.impl.ToolsImpl;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

/**
 * Created by jaylon on 16-1-6.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class FileHelper extends BaseHelper{

    private static final Logger logger = LoggerFactory.getLogger(FileHelper.class);

    public String saveFile(CommonsMultipartFile file){
        return saveLocalFile(file.getOriginalFilename(), file.getBytes());
    }

    private String getDirectory(byte[] data) {
        String checksum = ToolsImpl.sha256(data);

        // work out the path name
        // file name aabbccddee
        // path will be aa/bb/cc/dd/ee
        StringBuffer path = new StringBuffer();
        int startIndex = 0;
        int increment = 2;
        int endIndex = startIndex + increment;
        while (startIndex < checksum.length()) {
            if (endIndex > checksum.length()) {
                endIndex = checksum.length();
            }
            path.append(checksum.substring(startIndex, endIndex));

            startIndex = startIndex + increment;
            endIndex = endIndex + increment;
        }
        return path.toString();
    }

    private String saveLocalFile(String filename, byte[] data){
        UUID uuid =UUID.randomUUID();
        String address="/imgs"+File.separator+uuid+filename;
                String path = fileStorageRoot+File.separator+address;
        File file = new File(path.toString());
        if (!file.exists()) {
            try {
                FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
                fos.write(data);
                fos.close();
            } catch (Exception e) {
                logger.error("Error occured saving file [{}].", path.toString());
                logger.error("Exception: ", e);
            }
        }
        return address;
    }

}
